/**
 * Created by TomSean on 2017/11/10.
 */
var ShopVanManager = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
ShopVanManager.prototype = {
    init : function () {
        var $this = this;
        var /* 将.search-params里的参数绑定到kendo控件里 */ bindFieldArray = this.sysUtils.getBindFieldArray(this.$parent.find(".search-panel"));
        var /* 初始化按钮列表 */ bindFunctionArray = [
            {fName : "delete", fs : this.deleteData},
            {fName : "search", fs : this.findData},
            {fName : "reset_btn", fs : this.resetInfo}
        ];
        this.bindBaseModels = new bindBaseModel(null, bindFieldArray, bindFunctionArray, null);
        this.sysUtils.bindDoucment(this.bindBaseModels, this.$parent, this);
        var sHeight = (this.$parent.find('.search-panel')[0].clientHeight);
        var allHeight = (this.$parent[0].clientHeight);
        this.$parent.find('#shop_van_list').height(allHeight-sHeight-2);
        this.initTable();
        this.findData();
    },
    findData : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        var /* 从kendo控件里将绑定的参数转为json字符串 */ params = $this.sysUtils.getBindDocJson($this.bindBaseModels.bindFieldArray);
        if (validityForm($this.$parent)) {
            if(!isEmpty(params["minDate"])){
                params["minDate"] = params["minDate"].pattern("yyyy-MM-dd");
            }
            if(!isEmpty(params["maxDate"])){
                params["maxDate"] = params["maxDate"].pattern("yyyy-MM-dd");
            }
            var url = baseApiPath + "shopVan/findAll";
            var grid = $this.$parent.find("#shop_van_list").data("kendoGrid");
            var dataT = {curdatetime:new Date().getTime(), jsonParam:JSON.stringify(params)};
            var dataSource = $this.sysUtils.getDataSource({url : url, data : dataT, dataType : "odata"});
            grid.setDataSource(dataSource);
        }
    },
    addData : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        $this.openRemarkWindow();
    },
    updateData : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        var grid = $this.$parent.find("#shop_van_list").data("kendoGrid");
        var dataItem = grid.dataItem(grid.select());
        if (isEmpty(dataItem['ownerCode'])) {
            notification({'title':'警告', 'message':'请先选中需要修改的数据'}, 'info');
            return;
        }
        $this.openRemarkWindow(dataItem['ownerCode']);
    },
    deleteData : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        var ids = "";
        $this.$parent.find("input[name='shop_van_code']:checked").each(function(inx, itm) {
            var id = $(itm).val();
            ids += id + ",";
        });
        if (ids == "") {
            notification({ title:"操作失败", message:"请选择至少一条需要删除的记录!!"},'info');
            return;
        }
        notification({title:"确认信息", message:"确定需要删除选中的信息？"}, 'confirm', {
            callback : function(){
                JsonpAjax(baseApiPath + "shopVan/delete?ids="+ids,"","json",function(res){
                    $this.findData();
                });
            }
        });
    },
    /*
     * 重置按钮
     */
    resetInfo:function(e){
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.bindBaseModels.bindFieldArray);
    },
    initTable : /* 初始化表格(kendo-Grid) */ function() {
        var _this = this;
        var columns = [
            {
                width : 30,
                headerTemplate : '<input type="checkbox" gridId="shop_van_list" onclick="gridCheckAll(this)" />',
                template : '<input type="checkbox" name="shop_van_code" value="${ownerCode}" />'
            },
            {
                title : "车主编号",
                field : "ownerCode"
            },
            {
                title : "车主姓名",
                field : "ownerName"
            },
            {
                title : "拥有车辆",
                field : "vehicleNos"
            },
            {
                title : "联系电话",
                field : "ownerPhone"
            },
            {
                title : "创建时间",
                field : "createTime"
            },
            {
                title : "创建操作人",
                field : "createUsername"
            }
        ];
        this.sysUtils.createGird(
            this.$parent.find("#shop_van_list"),
            {
                selectable : 'single',
                autoSync : true,
                columnMenu : true,
                pageable : {input : true, numeric : false},
                columns : columns,
                change : function(e) {
                    var selected = $.map(this.select(), function(itm) {
                        return $(itm).find("input[type=checkbox]").val();
                    });
                    _this.selectRowId = selected[0];
                },
                dataBound : function() {
                    var $list = _this.$parent.find("#shop_van_list");
                    $list.find("tr").unbind("dblclick");
                    $list.find("tr").dblclick(function(e){
                        var grid = $list.data("kendoGrid");
                        var dataItem = grid.dataItem(grid.select());
                        //打开查看窗口
                        _this.isEdit = false;
                        _this.openReadWindow(dataItem["ownerCode"]);
                    });
                }
            }
        )
    },
    openRemarkWindow : function (code) {
        var _this = this;
        if (isEmpty(code)) {
            _this.editDiv = _this.sysUtils.openWindow(_this.editDiv, {
                title : "查看商铺车信息",
                height : "600px",
                width : "650px",
                resizable : false,
                content : "views/parkLotCenter/shopVan/shop_van_edit.html"
            }, true);
        } else {
            JsonpAjax(baseApiPath + "shopVan/" + code, null, "json", function(res) {
                _this.entity = res[0];
                _this.vehicleinfo = res[1];
                _this.editDiv = _this.sysUtils.openWindow(_this.editDiv, {
                    title : "查看商铺车信息",
                    height : "600px",
                    width : "650px",
                    resizable : false,
                    content : "views/parkLotCenter/shopVan/shop_van_edit.html"
                }, true);
            });
        }
    },

}

var ShopVanEdit = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
ShopVanEdit.prototype = {
    init : function () {
        var $this = this;
        // 添加车位事件
        this.$parent.find('.vehicle_div.add').bind('click', function(event) {
            console.log('add');
            var vehicle_div = '<div class="vehicle_div edit" data-new>';
            vehicle_div += '<a onclick="removeVehicleDiv(this)" class="delete_vehicle" style="display: block;"></a>';
            vehicle_div += '<label class="vehicle_no"><input type="text" placeholder="车牌号" /></label>';
            vehicle_div += '<table>';
            vehicle_div += '    <tr>';
            vehicle_div += '        <td>车辆品牌：</td>';
            vehicle_div += '        <td class="vehicle_category"><input type="text" /></td>';
            vehicle_div += '    </tr>';
            vehicle_div += '    <tr>';
            vehicle_div += '        <td>车牌颜色：</td>';
            vehicle_div += '        <td class="vehicle_logo"><input type="text" /></td>';
            vehicle_div += '    </tr>';
            vehicle_div += '    <tr>';
            vehicle_div += '        <td>车体类型：</td>';
            vehicle_div += '        <td class="vehicle_type">'+$this.getVehicleTypeSelect()+'</td>';
            vehicle_div += '    </tr>';
            vehicle_div += '    <tr>';
            vehicle_div += '        <td>车体颜色：</td>';
            vehicle_div += '        <td class="vehicle_color"><input type="text" /></td>';
            vehicle_div += '    </tr>';
            vehicle_div += '</table>';
            vehicle_div += '</div>';
            $(this).before(vehicle_div);
        });
        this.deployData(shopVanManager.entity);
        this.deployVehicle(shopVanManager.vehicleinfo);
    },
    // 部署值到表单
    deployData : function (data) {
        var $this = this;
        if (!isEmpty(data)) {
            $this.$parent.find('[name="ownerCode"]').val(data.ownerCode);
            $this.$parent.find('[name="ownerName"]').val(data.ownerName);
            $this.$parent.find('[name="ownerPhone"]').val(data.ownerPhone);
            $this.$parent.find('[name="ownerAddress"]').val(data.ownerAddress);
            if (!isEmpty(data.organization)) {
                $this.$parent.find('[name="organization_id"]').val(data.organization.organizationCode);
                var node = $this.organizationTree.ztree.getNodeByParam('id', data.organization.organizationCode);
                var names = '';
                while (true) {
                    if (names == '') {
                        names = node.fullName;
                    } else {
                        names = node.fullName + ' > ' + names;
                    }
                    if (!node.getParentNode() || node.getParentNode().level == 0) {
                        break;
                    }
                    node = node.getParentNode();
                }
                $this.$parent.find('#info-tree');
                $this.$parent.find('#organization_text').val(names);
            }
            $this.$parent.find('[name="remark"]').val(data.remark);
        }
    },
    // 获取车辆类型下拉
    getVehicleTypeSelect : function (opt) {
        var typeArray = Utils.getModelArrayByParentModelKey(BASIS.VEHICLE_TYPE.ROOT);
        var html = '<select>';
        for (var i = 0; i < typeArray.length; i++) {
            var selected = typeArray[i].modelName == opt ? 'selected' : '';
            html += '<option '+selected+' value="'+typeArray[i].modelValue+'">' + typeArray[i].modelName + '</option>';
        }
        html += '</select>';
        return html;
    },
    // 部署值到车辆
    deployVehicle : function (data) {
        var $this = this;
        if (!isEmpty(data)) {
            for (var i = 0; i < data.length; i++) {
                $this.addVehicle(data[i].vehicleNo, data[i].vehicleCategory, data[i].vehicleLogo, Utils.getModelNameByParentKey(BASIS.VEHICLE_TYPE.ROOT, data[i].vehicleType), data[i].vehicleType, data[i].vehicleColor);
            }
        }
    },
    addVehicle : function (no, category, logo, type_name, type_value, color) {
        var vehicle_div = '';
        vehicle_div += '<div class="vehicle_div">';
        vehicle_div += '<a onclick="removeVehicleDiv(this)" class="delete_vehicle"></a>';
        vehicle_div += '    <label class="vehicle_no"><input type="text" placeholder="车牌号" value="'+no+'" /></label>';
        vehicle_div += '    <table>';
        vehicle_div += '        <tr>';
        vehicle_div += '            <td>车辆品牌：</td>';
        vehicle_div += '            <td class="vehicle_category"><input type="text" value="'+category+'" /></td>';
        vehicle_div += '        </tr>';
        vehicle_div += '        <tr>';
        vehicle_div += '            <td>车牌颜色：</td>';
        vehicle_div += '            <td class="vehicle_logo"><input type="text" value="'+logo+'" /></td>';
        vehicle_div += '        </tr>';
        vehicle_div += '        <tr>';
        vehicle_div += '            <td>车体类型：</td>';
        vehicle_div += '            <td class="vehicle_type" data-value="'+type_value+'">'+this.getVehicleTypeSelect(type_name)+'</td>';
        vehicle_div += '        </tr>';
        vehicle_div += '        <tr>';
        vehicle_div += '            <td>车体颜色：</td>';
        vehicle_div += '            <td class="vehicle_color"><input type="text" value="'+color+'" /></td>';
        vehicle_div += '        </tr>';
        vehicle_div += '    </table>';
        vehicle_div += '</div>';
        this.$parent.find('.vehicle_div.add').before(vehicle_div);
    },
    // 保存车主信息
    saveOwnerInfo : function () {
        var entity = {};
        var ownerInfo = {};
        ownerInfo['ownerName'] = this.$parent.find('input[name="ownerName"]').val();
        ownerInfo['ownerPhone'] = this.$parent.find('input[name="ownerPhone"]').val();
        if(isEmpty(ownerInfo['ownerName'])) {
            notification({'title':'错误', 'message':'用户姓名不能为空！'},'error');
            return;
        }
        if (!(/^[\u4e00-\u9fa5\w\-]*$/.test(ownerInfo['ownerName']))) {
            notification({'title':'错误', 'message':'姓名只能为汉字大小写因为字母、数字、-、_'},'error');
            return;
        }
        if(!isEmpty(ownerInfo['ownerPhone']) && !(/^1[34578]\d{9}$/.test(ownerInfo['ownerPhone']))){
            notification({'title':'错误', 'message':'手机号码有误，请重填'}, 'error');
            return;
        }
        ownerInfo['ownerAddress'] = this.$parent.find('input[name="ownerAddress"]').val();
        ownerInfo['remark'] = this.$parent.find('textarea[name="remark"]').val();
        entity['van'] = ownerInfo;
        entity['vehicleArray'] = [];
        var tempVehicleNo = '';
        var flagStop = false;
        this.$parent.find('#owner_vehicles .vehicle_div').not('.add').each(function(inx, itm){
            var vehicle = {};
            vehicle['vehicleNo'] = $(itm).find('.vehicle_no input').val();
            if (tempVehicleNo.indexOf('['+vehicle['vehicleNo']+']') != -1) {
                notification({'title':'错误', 'message':'车牌重复入录！！！' + '['+vehicle['vehicleNo']+']'},'error');
                flagStop = true;
                return false;
            }
            tempVehicleNo += '['+vehicle['vehicleNo']+']';
            vehicle['vehicleCategory'] = $(itm).find('.vehicle_category input').val();
            vehicle['vehicleLogo'] = $(itm).find('.vehicle_logo input').val();
            vehicle['vehicleType'] = $(itm).find('.vehicle_type select').val();
            vehicle['vehicleColor'] = $(itm).find('.vehicle_color input').val();
            entity['vehicleArray'].push(vehicle);
        });
        if (flagStop) {
            return;
        }
        JsonpAjax(baseApiPath + 'shopVan/save?code=' + this.$parent.find('[name="ownerCode"]').val(), JSON.stringify(entity), 'json', function(res) {
            $('#' + shopVanManager.editDiv).data('kendoWindow').close();
            shopVanManager.findData();
        }, true);
    }
}